package cn.alm.allinoneboot.controller;

import cn.alm.allinoneboot.common.CommonResult;
import cn.alm.allinoneboot.entity.Category;
import cn.alm.allinoneboot.service.ApiService;
import cn.alm.allinoneboot.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("api/category")
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class CategoryController {

    @Resource
    ApiService apiService;

    @Resource
    CategoryService categoryService;

    // 查询分类树
    @PostMapping("getCategoryTree")
    public CommonResult getCategoryTree(@RequestHeader(value = "authorization", required = false) String authorization) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return categoryService.getCategoryTree();
    }

    // 添加分类
    @PostMapping("addCategory")
    public CommonResult addCategory(@RequestHeader(value = "authorization", required = false) String authorization, @RequestBody Category category) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return categoryService.addCategory(category);
    }

    // 更新分类
    @PostMapping("updateCategory")
    public CommonResult updateCategory(@RequestHeader(value = "authorization", required = false) String authorization, @RequestBody Category category) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return categoryService.updateCategory(category);
    }

    // 删除分类
    @PostMapping("deleteCategory")
    public CommonResult deleteCategory(@RequestHeader(value = "authorization", required = false) String authorization, @RequestBody Category category) {
        if (!apiService.tokenValid(authorization)) {
            CommonResult cr = new CommonResult();
            cr.unAuth();
            return cr;
        }
        return categoryService.deleteCategory(category);
    }


}
